package top.frsf.mqtt.handler.strategy;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.mqtt.MqttMessage;
import io.netty.handler.codec.mqtt.MqttMessageType;
import io.netty.handler.codec.mqtt.MqttPublishMessage;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import top.frsf.dashboard.config.BrokerStats;
import top.frsf.mqtt.handler.strategy.abs.MqttMessageHandlerStrategy;
import top.frsf.mqtt.session.SessionManager;

import java.util.Set;

/**
 * MQTT协议事件 - 发布事件处理器
 *
 * @author He Kuntao
 * @since 2025/5/29 14:55
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class PublishMessageHandler implements MqttMessageHandlerStrategy {

    private final SessionManager sessionManager;

    private final BrokerStats brokerStats;

    @Override
    public void handle(ChannelHandlerContext ctx, MqttMessage message) {
        MqttPublishMessage msg = (MqttPublishMessage) message;
        String topic = msg.variableHeader().topicName();
        log.info("Publish to topic: {}", topic);
        brokerStats.incrementMessagesReceived();

        // 简单分发消息给订阅者
        Set<String> subscribers = sessionManager.getSubscribers(topic);
        if (subscribers != null) {
            subscribers.forEach(clientId -> {
                Channel channel = sessionManager.getChannelByClientId(clientId);
                if (channel != null && channel.isActive()) {
                    msg.retain();
                    channel.writeAndFlush(msg);
                    brokerStats.incrementMessagesSent();
                }
            });
        }

    }

    @Override
    public MqttMessageType supportedType() {
        return MqttMessageType.PUBLISH;
    }
}
